package online.shuita.gitee.mojo.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class StringUtil {
    public final static Pattern pattern = Pattern.compile("(?<=\\{\\{)[^\\{\\}]*(?=\\}\\})");

    private StringUtil() {

    }

    /**
     * 处理模板字符串，替换变量
     *
     * @param temp    模板字符串
     * @param context 变量上下文
     * @return 返回替换过变量后的字符串
     */
    public static String procTemp(String temp, Map<String, String> context) {
        if (StringUtils.isNotEmpty(temp)) {
            log.info("temp is {}", temp);
            Matcher m = pattern.matcher(temp);
            while (m.find()) {
                String key = m.group();
                if (StringUtils.isEmpty(key)) {
                    continue;
                }
                Object val = context.get(key);
                if (null != val) {
                    temp = temp.replace("{{" + key + "}}", val.toString());
                }
            }
            log.info("warning message is {}", temp);
            return temp;
        }
        return null;
    }


    /**
     * "file:/home/whf/cn/fh" - "/home/whf/cn/fh" * "jar:file:/home/whf/foo.jar!cn/fh" - "/home/whf/foo.jar"
     * @param url 待处理的url
     * @return 处理后的url
     */
    public static String getRootPath(URL url) {
        String fileUrl = url.getFile();
        int pos = fileUrl.indexOf('!');

        if (-1 == pos) {
            return fileUrl;
        }

        return fileUrl.substring(5, pos);
    }

    /**
     * "cn.fh.lightning" - "cn/fh/lightning" *
     * @param name 待处理字符串
     * @return 处理后字符串
     */
    public static String dotToSplash(String name) {
        return name.replaceAll("\\.", "/");
    }

    /**
     * "Apple.class" - "Apple"
     * @param name 待处理字符串
     * @return 处理后字符串
     */
    public static String trimExtension(String name) {
        int pos = name.indexOf('.');
        if (-1 != pos) {
            return name.substring(0, pos);
        }

        return name;
    }

    /**
     * /application/home - /home
     * @param uri 待处理字符串
     * @return 处理后字符串
     */
    public static String trimURI(String uri) {
        String trimmed = uri.substring(1);
        int splashIndex = trimmed.indexOf('/');

        return trimmed.substring(splashIndex);
    }
}
